﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper.Internal.Mappers;
using ThridGroup.ERP.DTO;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace ThridGroup.ERP.RBAC
{
    public class UserServices : ApplicationService, UserIServices
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IRepository<User, int> _userServices;

        public UserServices(IRepository<User, int> userServices)
        {
            _userServices = userServices;
        }

        public async Task<int> AddUser(UserDTO user)
        {
            var useradd = ObjectMapper.Map<UserDTO, User>(user);
            var usercount = await _userServices.InsertAsync(useradd);
            return usercount == null ? 0 : 1;

        }

        public async Task<int> DeleteUser(int userId)
        {
            var result = _userServices.DeleteDirectAsync(m => m.Id == userId);
            return result == null ? 0 : 1;
        }

        public async Task<UserDTO> GetUser(int userId)
        {
            var user = await _userServices.FindAsync(m => m.Id == userId);
            var result = ObjectMapper.Map<User, UserDTO>(user);
            return result;

        }

        public async Task<List<UserDTO>> ShowUser(ShowUserDTO showUserDTO)
        {
            var userList = await _userServices.GetListAsync();
            userList = userList.WhereIf(!string.IsNullOrEmpty(showUserDTO.UserName), m => m.UserName.Contains(showUserDTO.UserName)).ToList();
            userList = userList.WhereIf(!string.IsNullOrEmpty(showUserDTO.UserNickName), m => m.UserNickName.Contains(showUserDTO.UserNickName)).ToList();
            var result = ObjectMapper.Map<List<User>, List<UserDTO>>(userList);
            return result;
        }

        public async Task<int> UpdateUser(UserDTO user)
        {
            var useradd = ObjectMapper.Map<UserDTO, User>(user);
            var usercount = await _userServices.UpdateAsync(useradd);
            return usercount == null ? 0 : 1;
        }
    }
}
